package com.flca.frw.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

public class CSVReader extends BufferedReader {
	private char textQualifier = 0;
	private char delimiter;
	private String reSplit;
	private String reTrim;
	
	public CSVReader(Reader f) {
		this(f, ',');
	}
	
	public CSVReader(Reader f, char delimiter) {
		super(f);
		this.delimiter = delimiter;
		setupRegEx();
	}
	
	public CSVReader(Reader f, char delimiter, char textQualifier) {
		this(f, delimiter);
		this.textQualifier = textQualifier;
		setupRegEx();
	}
	
	private void setupRegEx() {
		StringBuilder b = new StringBuilder();
		if (textQualifier != 0) {
			b.append(textQualifier);
		}
		b.append(delimiter);
		if (textQualifier != 0) {
			b.append(textQualifier);
		}
		reSplit = b.toString();
		
		if (textQualifier != 0) {
			b.setLength(0);
			b.append("(^");
			b.append(textQualifier);
			b.append(")|(");
			b.append(textQualifier);
			b.append("$)");
			reTrim = b.toString();
		} else {
			reTrim = null;
		}
	}
	
	public String[] readRecord() throws IOException {
		String[] record = null;
		String line = readLine();
		if (line != null) {
			if (textQualifier != 0) {
				line = line.replaceAll(reTrim, "");
			}
			record = line.split(reSplit);
		}
		return record;
	}
}
